from django.shortcuts import render
from .models import *
from .serializer import *
from users.serializer import UserSer,UserDetailedSer
from users.models import UserDetailedModel,UserModel,TeacherGradeModel,GradeMode
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from rest_framework.viewsets import ViewSet
from rest_framework import status
from utlis.user_login import check_login
import json


# 获取所有资源数据信息
class LearningMaterialsSet(ModelViewSet):
    queryset = LearningMaterialsModel.objects.filter(is_delete=False).all()
    serializer_class = LearningMaterialSer

    # 获取资源
    def list(self, request, *args, **kwargs):
        try:
            queryset = LearningMaterialsModel.objects.filter(is_delete=False).all()
            lear_mate_ser = LearningMaterialSer(queryset, many=True).data
            lear_mate_list = json.loads(json.dumps(lear_mate_ser))
            print('lear_mata', lear_mate_list)
            for i in lear_mate_list:
                user = UserModel.objects.filter(id=i['user_id'],is_delete=False).all()
                user_ser = UserSer(user, many=True).data
                for j in user_ser:
                    user_data = UserDetailedModel.objects.filter(user_id=j['id'], is_delete=False).all()
                    user_data_ser = UserDetailedSer(user_data,many=True).data
                    print('user_data', user_data_ser)
                    j['user_data'] = user_data_ser
                i['user_list'] = user_ser

            return Response({
                "code": status.HTTP_200_OK,
                "message": "获取资源信息成功！",
                "lear_mate": lear_mate_list
            })
        except Exception as e:
            print(f"错误>>>{e}")
            return Response({
                "code": status.HTTP_500_INTERNAL_SERVER_ERROR,
                "message": f"服务器错误{e}"
            })


# 分类
class ClassSet(ModelViewSet):
    queryset = ClassModel.objects.filter(is_delete=False).all()
    serializer_class = ClassSer

    # 添加分类
    @check_login
    def create(self, request, *args, **kwargs):
        try:
            name = request.data.get('name')
            user_id = request.user
            user = UserModel.objects.filter(id=user_id, is_delete=False,position_id=3).first()
            if not user:
                return Response({"code": status.HTTP_204_NO_CONTENT, "message": "用户不符合要求！"})
            school_id = user.school_id
            if ClassModel.objects.filter(is_delete=False, name=name, school_id=school_id):
                return Response({"code": status.HTTP_204_NO_CONTENT, "message": "分类名已存在"})
            ClassModel.objects.create(name=name, school_id=school_id)
            return Response({"code": status.HTTP_200_OK, "message": "添加分类成功！"})
        except Exception as e:
            print("错误>>>", e)
            return Response({
                "code": status.HTTP_500_INTERNAL_SERVER_ERROR,
                "message": f"服务器错误{e}"
            })

    # 获取分类数据
    @check_login
    def list(self, request, *args, **kwargs):
        try:
            user_id = request.user
            user = UserModel.objects.filter(id=user_id, is_delete=False, position_id=3).first()
            school_id = user.school_id
            class_data = ClassModel.objects.filter(school_id=school_id,is_delete=False).all()
            class_ser = ClassSer(class_data, many=True).data
            return Response({"code": status.HTTP_200_OK, "message": "获取成功！", "class_data": class_ser})
        except Exception as e:
            print('错误>>>', e)
            return Response({
                "code":status.HTTP_500_INTERNAL_SERVER_ERROR,
                "message": f"服务器错误{e}"
            })


# 修改删除分类
class ClassOper(ViewSet):
    # 删除分类
    @check_login
    def delete(self, request, pk):
        try:
            user_id = request.user
            if not UserModel.objects.filter(id=user_id, is_delete=False, position_id=3):
                return Response({"code": status.HTTP_204_NO_CONTENT, "message": "用户不符合要求"})
            ClassModel.objects.filter(id=pk,is_delete=False).update(is_delete=True)
            return Response({
                "code": status.HTTP_200_OK,
                "message": "删除分类成功！"
            })
        except Exception as e:
            print('错误', e)
            return Response({
                "code": status.HTTP_500_INTERNAL_SERVER_ERROR,
                "message": f"服务器错误{e}"
            })

    # 修改分类
    @check_login
    def update(self, request, pk):
        try:
            name = request.data.get("name")
            user_id = request.user
            if not UserModel.objects.filter(id=user_id, is_delete=False, position_id=3):
                return Response({"code": status.HTTP_204_NO_CONTENT, "message": "用户不符合要求"})
            ClassModel.objects.filter(id=pk, is_delete=False).update(name=name)
            return Response({
                "code": status.HTTP_200_OK,
                "message": "修改分类成功！"
            })
        except Exception as e:
            print('错误>>', e)
            return Response({
                "code": status.HTTP_500_INTERNAL_SERVER_ERROR,
                "message": f"服务器错误{e}"
            })


# 发布学习内容
class StudyContentSet(ModelViewSet):
    queryset = StudyContentModel.objects.filter(is_delete=False).all()
    serializer_class = StudyContentSer

    @check_login
    def create(self, request, *args, **kwargs):
        try:
            user_id = request.user
            title = request.data.get("title")
            content = request.data.get("content")
            desc = request.data.get("desc")
            class_id = request.data.get("class_id")
            is_overt = request.data.get("is_overt")
            label = request.data.get("label")
            label_id = request.data.get("label_id")

            user = UserModel.objects.filter(id=user_id, is_delete=False, position_id=3).first()
            if not user:
                return Response({"code": status.HTTP_204_NO_CONTENT, "message": "用户不符合要求！"})

            if StudyContentModel.objects.filter(user_id=user_id,title=title,is_delete=False):
                return Response({
                    "code": status.HTTP_204_NO_CONTENT,
                    "message": "这个文章已经发布过了,请换个话题！"
                })

            if label != "":
                labels = LabelModel.objects.filter(name=label,is_delete=False).first()
                if not labels:
                    label_id_id = LabelModel.objects.create(name=label)
                    StudyContentModel.objects.create(title=title, content=content, desc=desc, class_id=class_id, label=label,
                                                 user_id=user_id,is_overt=is_overt, label_id=label_id_id)
                StudyContentModel.objects.create(title=title, content=content, desc=desc, class_id=class_id,
                                                 label=label,user_id=user_id, is_overt=is_overt, label_id=labels.id)

            if label_id != "":
                StudyContentModel.objects.create(title=title, content=content, desc=desc, class_id=class_id, label_id=label_id,
                                                 user_id=user_id, is_overt=is_overt)
            return Response({
                "code": status.HTTP_200_OK,
                "message": "发布学习内容成功！"
            })
        except Exception as e:
            print("错误>>>", e)
            return Response({
                "code": status.HTTP_500_INTERNAL_SERVER_ERROR,
                "message": f"服务器错误{e}"
            })

    # 获取用户发布的
    @check_login
    def list(self, request, *args, **kwargs):
        try:
            user_id = request.user
            study_content = StudyContentModel.objects.filter(user_id=user_id, is_delete=False).all()
            study_content_ser = StudyContentSer(study_content,many=True).data
            return Response({
                "code": status.HTTP_200_OK,
                "message": "获取学习内容成功！",
                "data": study_content_ser
            })
        except Exception as e:
            print("错误>>", e)
            return Response({
                "code": status.HTTP_500_INTERNAL_SERVER_ERROR,
                "message": f"服务器错误{e}"
            })


# 学习内容操作
class OperStudyContent(ViewSet):
    # 删除学习内容
    @check_login
    def delete(self, request, pk):
        try:
            user_id = request.user
            user = UserModel.objects.filter(id=user_id, is_delete=False, position_id=3).first()
            if not user:
                return Response({"code": status.HTTP_204_NO_CONTENT, "message": "用户不符合要求"})

            StudyContentModel.objects.filter(id=pk,is_delete=False).update(is_delete=True)
            StudyTaskModel.objects.filter(study_content_id=pk, is_delete=False).update(is_delete=True)
            LearningMaterialsModel.objects.filter(study_id=pk, is_delete=False).update(is_delete=True)
            return Response({
                "code": status.HTTP_200_OK,
                'message': "删除成功！"
            })
        except Exception as e:
            print("错误>>>", e)
            return Response({
                "code": status.HTTP_500_INTERNAL_SERVER_ERROR,
                "message": f"服务器错误{e}"
            })

    # 修改学习内容
    @check_login
    def update(self, request, pk):
        try:
            user_id =request.user
            title = request.data.get("title")
            content = request.data.get("content")
            desc = request.data.get("desc")
            class_id = request.data.get("class_id")
            label = request.data.get("label")
            label_id = request.data.get("label_id")

            if not StudyContentModel.objects.filter(user_id=user_id,is_delete=False):
                return Response({"code": status.HTTP_204_NO_CONTENT, "message": "用户不符合要求！"})

            if label != "":
                labels = LabelModel.objects.filter(name=label,is_delete=False).first()
                if not labels:
                    label_id_id = LabelModel.objects.create(name=label)
                    StudyContentModel.objects.filter(id=pk, is_delete=False).update(title=title, content=content,desc=desc, class_id=class_id,
                                                                                   label=label,label_id=label_id_id)
                StudyContentModel.objects.filter(id=pk,is_delete=False).update(title=title, content=content, desc=desc, class_id=class_id,
                                                                                label=label,user_id=user_id, label_id=labels.id)

            if label_id != "":
                StudyContentModel.objects.filter(id=pk,is_delete=False).update(title=title, content=content, desc=desc, class_id=class_id, label_id=label_id,
                                                                                user_id=user_id)

            return Response({"code": status.HTTP_200_OK, "message": "修改成功！"})

        except Exception as e:
            print('错误>>', e)
            return Response({
                "code": status.HTTP_500_INTERNAL_SERVER_ERROR,
                "message": f"服务器错误{e}"
            })


# 获取学习任务详情
class Study(APIView):
    def get(self, request, pk):
        study = StudyContentModel.objects.filter(id=pk,is_delete=False,is_overt=False).first()
        print('study', study)
        study_ser = StudyContentSer(study).data
        print('study_ser', study_ser)
        user_id = study_ser['user_id']
        user = UserDetailedModel.objects.filter(user_id=user_id, is_delete=False).all()
        user_ser = UserDetailedSer(user,many=True).data
        study_ser['user_data'] = user_ser
        return Response({
            "code": status.HTTP_200_OK,
            "message": "获取任务详情成功！",
            "data": study_ser
        })


# 设置学习任务状态
class OpenStudy(APIView):
    @check_login
    def put(self,request, pk):
        try:
            user_id =request.user
            is_overt = request.data.get('is_overt')
            if not UserModel.objects.filter(id=user_id, is_delete=False, position_id=3):
                return Response({"code": status.HTTP_204_NO_CONTENT, "message": "用户不符合要求"})
            if not StudyContentModel.objects.filter(id=pk, is_delete=False, user_id=user_id):
                return Response({"code": status.HTTP_204_NO_CONTENT, "message": "信息不存在"})
            if int(is_overt) == 1:
                StudyContentModel.objects.filter(id=pk).update(is_overt=False)
                return Response({"code": status.HTTP_200_OK, 'message': '内容已公开'})
            if int(is_overt) == 0:
                StudyContentModel.objects.filter(id=pk).update(is_overt=True)
                return Response({'code': status.HTTP_200_OK, "message": "内容已隐藏"})
            return Response({"code": status.HTTP_204_NO_CONTENT,'message': '数据错误'})
        except Exception as e:
            print('错误>>', e)
            return Response({
                "code": status.HTTP_500_INTERNAL_SERVER_ERROR,
                "message": f"服务器错误{e}"
            })


# 发布资源
class PublishResource(APIView):
    @check_login
    def post(self, request):
        try:
            user_id =request.user
            study_id = request.data.get("study_id")
            price = request.data.get("price")
            image = request.data.get("image")

            study = StudyContentModel.objects.filter(id=study_id, user_id=user_id, is_delete=False, is_overt=False).filter()

            if not study:
                return Response({"code": status.HTTP_204_NO_CONTENT, "message": "不符合要求"})

            if LearningMaterialsModel.objects.filter(study_id=study_id, is_delete=False):
                return Response({
                    "code": status.HTTP_204_NO_CONTENT,
                    'message': "该资源已经发布了,请不要重复发送,占用公海"
                })
            desc = study.desc
            name = study.title

            LearningMaterialsModel.objects.create(user_id=user_id, study_id=study_id,price=price,desc=desc,
                                                  image=image, name=name)
            return Response({"code": status.HTTP_200_OK, "message": "发布资源成功"})
        except Exception as e:
            print("错误>>>", e)
            return Response({
                "code": status.HTTP_500_INTERNAL_SERVER_ERROR,
                "message": f"服务器错误{e}"
            })


# 分享学习内容
class ShareTaskAPIView(APIView):
    @check_login
    def post(self, request):
        try:
            user_id = request.user
            study_id = request.data.get("study_id")
            grade_id = request.data.get("grade_id")
            user = UserModel.objects.filter(id=user_id,is_delete=False).first()

            if not GradeMode.objects.filter(school_id=user.school_id,is_delete=False):
                return Response({"code": status.HTTP_204_NO_CONTENT, "message": "请分享到自己所在学校的班级！"})

            study = StudyContentModel.objects.filter(user_id=user_id, id=study_id,is_delete=False, is_overt=False).first()
            if not study:
                return Response({"code": status.HTTP_204_NO_CONTENT, "message": "不符合要求，不能分享"})

            if not TeacherGradeModel.objects.filter(user_id=user_id, grade_id=grade_id,is_delete=False):
                return Response({"code": status.HTTP_204_NO_CONTENT, 'message': "请分享给自己管理的班级！"})

            if StudyTaskModel.objects.filter(study_id=study_id, grade_id=grade_id, user_id=user_id, is_delete=False):
                return Response({"code": status.HTTP_200_OK, "message": "任务已存在"})

            StudyTaskModel.objects.create(user_id=user_id, study_content_id=study_id, grade_id=grade_id)
            StudyContentModel.objects.filter(id=study_id, is_delete=False, is_overt=False).update(is_share=False)
            return Response({
                "code": status.HTTP_200_OK,
                "message": '发布任务成功！'
            })
        except Exception as e:
            print('错误>>>', e)
            return Response({"code": status.HTTP_200_OK, "message": f"服务器错误{e}"})


# 查看未发布的任务
class NotShareTask(APIView):
    @check_login
    def get(self, request):
        try:
            user_id = request.user

            study = StudyContentModel.objects.filter(user_id=user_id, is_delete=False, is_overt=False, is_share=True).all()
            study_ser = StudyContentSer(study, many=True).data
            return Response({
                "code": status.HTTP_200_OK,
                "message": "获取未分享内容成功！",
                "data": study_ser
            })
        except Exception as e:
            print("错误>>>", e)
            return Response({
                "code": status.HTTP_500_INTERNAL_SERVER_ERROR,
                "message": f"服务器错误{e}"
            })


# 获取自己待完成的任务
# TODO 后面写


# 获取搜索记录
class SearchAPIView(APIView):
    @check_login
    def get(self, request):
        user_id = request.user
        content = request.data.get("content")

        learning = LearningMaterialsModel.objects.filter(name__contains=content, is_delete=False).all()
        learning_ser = LearningMaterialSer(learning, many=True).data
        SearchHistoryModel.objects.create(user_id=user_id, content=content)
        return Response({
            "code": status.HTTP_200_OK,
            'message': "搜索完成",
            "data": learning_ser
        })


# 点赞学习内容
class LikeStudy(APIView):
    @check_login
    def post(self, request):
        try:
            user_id = request.user
            study_id = request.data.get("study_id")

            if not StudyContentModel.objects.filter(id=study_id, is_delete=False, is_overt=False):
                return Response({
                    "code": status.HTTP_204_NO_CONTENT,
                    'message': '不符合点赞要求'
                })

            if LikeModel.objects.filter(user_id=user_id, study_content_id=study_id,is_delete=False):
                LikeModel.objects.filter(user_id=user_id, study_content_id=study_id).update(is_delete=True)
                return Response({"code": status.HTTP_200_OK,'message': "取消点赞成功"})
            if LikeModel.objects.filter(user_id=user_id, study_content_id=study_id,is_delete=True):
                LikeModel.objects.filter(user_id=user_id, study_content_id=study_id).update(is_delete=False)
                return Response({"code": status.HTTP_200_OK,"message": "点赞成功"})
            if not LikeModel.objects.filter(user_id=user_id, study_content_id=study_id):
                LikeModel.objects.create(user_id=user_id, study_content_id=study_id)
                return Response({"code": status.HTTP_200_OK, "message":"点赞成功"})
            return Response({
                "code": status.HTTP_200_OK,
                "message": "出错了，过一会再试吧"
            })
        except Exception as e:
            print("错误>>>", e)
            return Response({
                "code": status.HTTP_500_INTERNAL_SERVER_ERROR,
                "message": f"服务器错误{e}"
            })


# 收藏内容
class CollectStudy(ViewSet):
    @check_login
    def create(self, request):
        try:
            user_id = request.user
            study_id = request.data.get("study_id")

            if not StudyContentModel.objects.filter(id=study_id, is_delete=False, is_overt=False):
                return Response({
                    "code": status.HTTP_204_NO_CONTENT,
                    'message': '不符合收藏要求'
                })

            if CollectModel.objects.filter(user_id=user_id, study_content_id=study_id,is_delete=False):
                CollectModel.objects.filter(user_id=user_id, study_content_id=study_id).update(is_delete=True)
                return Response({"code": status.HTTP_200_OK,'message': "取消收藏成功"})
            if CollectModel.objects.filter(user_id=user_id, study_content_id=study_id,is_delete=True):
                CollectModel.objects.filter(user_id=user_id, study_content_id=study_id).update(is_delete=False)
                return Response({"code": status.HTTP_200_OK,"message": "收藏成功"})
            if not CollectModel.objects.filter(user_id=user_id, study_content_id=study_id):
                CollectModel.objects.create(user_id=user_id, study_content_id=study_id)
                return Response({"code": status.HTTP_200_OK, "message":"收藏成功"})
            return Response({
                "code": status.HTTP_200_OK,
                "message": "出错了，过一会再试吧"
            })
        except Exception as e:
            print("错误>>>", e)
            return Response({
                "code": status.HTTP_500_INTERNAL_SERVER_ERROR,
                "message": f"服务器错误{e}"
            })

    # 查看收藏的内容
    @check_login
    def list(self, request):
        try:
            user_id =request.user
            collect = CollectModel.objects.filter(user_id=user_id, is_delete=False).all()
            collect_ser = CollectSer(collect, many=True).data
            collect_list = json.loads(json.dumps(collect_ser))
            data_list = []
            for i in collect_list:
                study = StudyContentModel.objects.filter(id=i['study_content_id'], is_delete=False).first()
                study_ser = StudyContentSer(study).data
                data_list.append(study_ser)

            return Response({
                "code": status.HTTP_200_OK,
                "message": "获取成功！",
                "data": data_list
            })
        except Exception as e:
            print("错误>>>", e)
            return Response({
                "code": status.HTTP_500_INTERNAL_SERVER_ERROR,
                "message": f"服务器错误{e}"
            })


